import serial

# 初始化串口
def Serial_init():

    port = 'COM5'  # 串口号，根据实际情况修改
    # port = '/dev/carserial'  # 串口号，根据实际情况修改
    baudrate = 115200  # 波特率，根据实际情况修改
    timeout = 1  # 超时时间

    try:
        ser = serial.Serial(port, baudrate, timeout=timeout)
        print(f"串口 {port} 已打开，波特率为 {baudrate}。")
        return ser
    except (OSError, serial.SerialException) as e:  # 兼容不同异常处理
        print(f"打开串口失败：{e}")
        return None

# 发送十六进制数据到串口
def Serial_send_hex(hex_data):

    try:
        # 将十六进制字符串转换为字节数据
        byte_data = bytes.fromhex(hex_data)
        ser.write(byte_data)  # 发送字节数据
        print(f"发送十六进制数据：{hex_data}")
    except (OSError, serial.SerialException) as e:
        print(f"发送数据失败：{e}")
    except ValueError as e:
        print(f"无效的十六进制数据：{e}")

def send_command(command,value=0):
    if command == 'x':
        command = "00"
        value = "00"
        tt = f"AA BB 06 11 {command} {value} 40 00"
        Serial_send_hex(tt)
    else:
        if command == 'w':
            command = "01"
        elif command == 's':
            command = "02"
        elif command == 'a':
            command = "03"
        elif command == 'd':
            command = "04"
        elif command == 'q':
            command = "05"
        elif command == 'e':
            command = "06"

        tt = f"AA BB 06 11 02 {command} {value} 00"
        Serial_send_hex(tt)


